<template>
  <div>
    <h2 style="text-align:center;">康复治疗排班表</h2>
    <div class="head-container">
      <!-- 标题 -->
      <!-- 查询表单 -->
      <div label="排班日期">
        <el-date-picker v-model="queryData.date" :default-value="new Date()" type="date"
          placeholder="查询日期"></el-date-picker>
      </div>
      <el-radio-group v-model="queryData.time">
        <el-radio-button label="全天">全天</el-radio-button>
        <el-radio-button label="上午">上午</el-radio-button>
        <el-radio-button label="下午">下午</el-radio-button>
      </el-radio-group>
      <div v-if="queryTab === '按治疗师查询'">
        <el-input v-model="queryData.doctorname" placeholder="请输入治疗师姓名查询"></el-input>
        <el-button type="primary" @click="queryDoctorSchedule" class="chaxun">查询排班</el-button>
      </div>
      <div v-if="queryTab === '按设备查询'">
        <el-input v-model="queryData.devicename" placeholder="请输入治疗设备查询"></el-input>
        <el-button type="primary" @click="queryDeviceSchedule" class="chaxun">查询排班</el-button>
      </div>
      <el-button type="primary" @click="addSchedule" class="xinzeng">新增排班</el-button>
    </div>

    <!-- <div v-if="activeRow2" class="patient-info-container">
            <p class="patient-info-item">
                <span class="info-label">当前病人：</span>
                <span class="info-value">{{ activeRow.patientName }}</span>
            </p>
            <p class="patient-info-item">
                <span class="info-label">当前病人id：</span>
                <span class="info-value">{{ activeRow.patientId }}</span>
            </p>
            <p class="patient-info-item">
                <span class="info-label">当前病人hisPatientId：</span>
                <span class="info-value">{{ activeRow.hisPatientId }}</span>
            </p>
            <p class="patient-info-item">
                <span class="info-label">治疗项目：</span>
                <span class="info-value">{{ activeRow2.treatmentName }}</span>
            </p>
        </div> -->

    <!-- 排班表 -->
    <div style="" v-loading="loading">
      <el-tabs type="border-card" @tab-click="handlequeryTabClick">
        <!-- 按治疗师查询 -->
        <el-tab-pane label="按治疗师查询" :lazy="true">
          <div v-if="queryTab === '按治疗师查询'">
            <div>
              <el-table ref="scheduleTable" :data="tableDoctorData" style="width:100%"
                :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
                @cell-click="handleDoctorCellClick" header-cell-class="table_header" :cell-style="cellStyle">
                <el-table-column prop="therapistName" label="治疗师姓名" width="120"></el-table-column>
                <el-table-column prop="scheduleDate" label="日期" width="100"></el-table-column>
                <el-table-column v-if="queryData.time === '全天' || queryData.time === '上午'" label="上午">
                  <el-table-column v-for="slot in timeSlots.slice(0, 8)" :key="slot.label" :prop="slot.value.toString()"
                    :label="slot.display" min-width="200" max-width="300">
                    <template slot-scope="scope"
                      v-if="scope.row[slot.value.toString()] && scope.row[slot.value.toString()].trim() !== ''">
                      <div class="card-style">{{
                        scope.row[slot.value.toString()] }}</div>
                    </template></el-table-column>
                </el-table-column>
                <el-table-column v-if="queryData.time === '全天' || queryData.time === '下午'" label="下午">
                  <el-table-column v-for="slot in timeSlots.slice(8)" :key="slot.label" :prop="slot.value.toString()"
                    :label="slot.display" min-width="200" max-width="300">
                    <template slot-scope="scope"
                      v-if="scope.row[slot.value.toString()] && scope.row[slot.value.toString()].trim() !== ''">
                      <div class="card-style">{{
                        scope.row[slot.value.toString()] }}</div>
                    </template></el-table-column>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <!-- 分页组件，用于数据分页展示 -->
          <el-pagination @size-change="handleDoctorSizeChange" @current-change="handleDoctorCurrentChange"
            :current-page="doctorpage" :page-sizes="[5, 10, 20, 30, 50]" :page-size="doctorsize"
            layout="total, sizes, prev, pager, next, jumper" :total="doctortotal">
          </el-pagination>
        </el-tab-pane>
        <!-- 按设备查询 -->
        <el-tab-pane label="按设备查询" :lazy="true">
          <div v-if="queryTab === '按设备查询'">
            <div>
              <el-table ref="scheduleTable" :data="tableDeviceData" style="width:100%"
                :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
                @cell-click="handleDeviceCellClick" header-cell-class="table_header" :cell-style="cellStyle">
                <el-table-column prop="equipmentName" label="治疗设备/治疗室" width="120"></el-table-column>
                <el-table-column prop="scheduleDate" label="日期" width="70"></el-table-column>
                <el-table-column v-if="queryData.time === '全天' || queryData.time === '上午'" label="上午">
                  <el-table-column v-for="slot in timeSlots.slice(0, 8)" :key="slot.label" :prop="slot.value.toString()"
                    :label="slot.display" min-width="200" max-width="300">
                    <template slot-scope="scope"
                      v-if="scope.row[slot.value.toString()] && scope.row[slot.value.toString()].trim() !== ''">
                      <div class="card-style">{{
                        scope.row[slot.value.toString()] }}</div>
                    </template></el-table-column>
                </el-table-column>
                <el-table-column v-if="queryData.time === '全天' || queryData.time === '下午'" label="下午">
                  <el-table-column v-for="slot in timeSlots.slice(8)" :key="slot.label" :prop="slot.value.toString()"
                    :label="slot.display" min-width="200" max-width="300">
                    <template slot-scope="scope"
                      v-if="scope.row[slot.value.toString()] && scope.row[slot.value.toString()].trim() !== ''">
                      <div class="card-style">{{
                        scope.row[slot.value.toString()] }}</div>
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <el-pagination @size-change="handleDeviceSizeChange" @current-change="handleDeviceCurrentChange"
            :current-page="devicepage" :page-sizes="[10, 20, 30, 50]" :page-size="devicesize"
            layout="total, sizes, prev, pager, next, jumper" :total="devicetotal">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 弹出对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" @close="clearFormValidate" append-to-body>
      <el-form :model="detailForm" ref="editFormRef" label-width="100px" :rules="editRules">
        <el-row>
          <el-col :span="24">
            <!-- <p>临时展示：
                            当前医师/治疗设备：（{{ currentRowLabel }}）,当前时段：（{{ currentColumnLabel }}）,当前病人（{{
                                currentPatient }}）</p> -->
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="治疗项目：">
              <el-input v-model="detailForm.detailFormtreatmentName" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医生姓名：" :rules="editRules.detailFormtherapistId" prop="detailFormtherapistId">
              <el-select v-model="detailForm.detailFormtherapistId" placeholder="" filterable>
                <template slot-scope="option">
                  <el-option v-for="option in therapistOptions" :key="option.id" :label="option.name"
                    :value="option.value">
                    <span>{{ option.name }}</span>
                    <span style="float: right; color: #999;">{{ option.id }}</span>
                  </el-option> </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="日期：">
              <el-date-picker v-model="detailForm.detailFormscheduleDate" type="date" placeholder=""
                class="detialdate"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="病人姓名：">
              <el-input v-model="detailForm.detailFormpatientName" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="病人id：">
              <el-input v-model="detailForm.detailFormpatientId" placeholder=""></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="治疗室：">
              <el-select v-model="detailForm.detailFormtreatmentRoomName" placeholder="请选择治疗室" filterable
                @change="handleTreatmentRoomChange">
                <el-option v-for="room in treatmentRoomOptions" :key="room.id" :label="room.treatmentRoomName"
                  :value="room.treatmentRoomName">
                  {{ room.treatmentRoomName }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"><el-form-item
              v-if="detailForm.detailFormtreatmentRoomName && detailForm.detailFormequipmentName" label="治疗设备：">
              <el-select v-model="detailForm.detailFormequipmentName" placeholder="请选择治疗设备">
                <el-option v-for="(equipment, index) in equipmentOptions" :key="index" :label="equipment"
                  :value="equipment">
                  {{ equipment }}
                </el-option>
              </el-select>
            </el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="时间段：">
              <el-select v-model="detailForm.detailFormscheduleTimeType" placeholder="请选择时间段">
                <el-option v-for="slot in timeSlots" :key="slot.value" :label="slot.display" :value="slot.value">
                  {{ slot.display }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="治疗时长：（未有字段）">
              <el-select v-model="detailForm.treatmentDuration" placeholder="请选择治疗时长">
                <el-option label="半小时" value="0.5"></el-option>
                <el-option label="一小时" value="1"></el-option>
                <el-option label="一个半小时" value="1.5"></el-option>
                <el-option label="两个小时" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述：">
              <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" placeholder=""
                v-model="detailForm.description">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :type="isAddMode ? 'primary' : 'warning'"
          @click="isAddMode ? saveSchedule('editFormRef') : updateSchedule('editFormRef')">
          {{ isAddMode ? '新增' : '更新' }}
        </el-button>
        <el-button type="danger" @click="delSchedule()">删除</el-button>
        <el-button type="">重置</el-button>
      </span>
    </el-dialog>

    <!-- 选择病人 -->
    <el-dialog title="选择预约病人" append-to-body :visible.sync="patientSelectionVisible" width="30%">
      <div>
        <el-select v-model="selectPatient" placeholder="请选择">
          <el-option v-for="item in batchData" :key="item.batchId" :label="item.patientName" :value="item.batchId">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="patientSelectionVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPatient">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import moment from 'moment';
import { queryAllTherapistScheduleInfo, queryAllEquipmentScheduleInfo, updateScheduleInfo, deleteScheduleInfo, addScheduleInfo, queryAllTreatmentRoomNameAndId, queryAllTherapistInfo } from "@/api/schedule/scheduleManagement/info.js"
export default {
  name: 'batchContextOwenr',
  data() {
    return {
      selectPatient: null, // 病人列表
      patientSelectionVisible: false, // 是否显示选择病人弹窗
      editRowColumn: { row: {}, column: {} },
      loading: false,
      //排班管理
      queryData: {
        // date: new Date(),//默认全天
        date: "",
        time: "全天",
        doctorname: "",
        devicename: "",
        deviceType: '',
      },
      //各个时间段对应的时间label和value{label:"8:00~8:30",value:1，display:"8:00~8:30"}
      timeSlots: [
        {
          label: "8:00~8:30",
          value: 1,
          display: "8:00~8:30"
        },
        {
          label: "8:30~9:00",
          value: 2,
          display: "8:30~9:00"
        },
        {
          label: "9:00~9:30",
          value: 3,
          display: "9:00~9:30"
        },
        {
          label: "9:30~10:00",
          value: 4,
          display: "9:30~10:00"
        },
        {
          label: "10:00~10:30",
          value: 5,
          display: "10:00~10:30"
        },
        {
          label: "10:30~11:00",
          value: 6,
          display: "10:30~11:00"
        },
        {
          label: "11:00~11:30",
          value: 7,
          display: "11:00~11:30"
        },
        {
          label: "11:30~12:00",
          value: 8,
          display: "11:30~12:00"
        },
        {
          label: "13:30~14:00",
          value: 9,
          display: "13:30~14:00"
        },
        {
          label: "14:00~14:30",
          value: 10,
          display: "14:00~14:30"
        },
        {
          label: "14:30~15:00",
          value: 11,
          display: "14:30~15:00"
        },
        {
          label: "15:00~15:30",
          value: 12,
          display: "15:00~15:30"
        },
        {
          label: "15:30~16:00",
          value: 13,
          display: "15:30~16:00"
        },
        {
          label: "16:00~16:30",
          value: 14,
          display: "16:00~16:30"
        },
        {
          label: "16:30~17:00",
          value: 15,
          display: "16:30~17:00"
        },
        {
          label: "17:00~17:30",
          value: 16,
          display: "17:00~17:30"
        }
      ],
      dialogVisible: false,
      detailForm: {
        treatmentDuration: '0.5', // 默认选择半小时
      },
      currentRowLabel: '',
      currentColumnLabel: '',
      currentPatient: '',
      currentScheduleId: '',
      queryTab: '按治疗师查询',//排班管理里的tab：按治疗师查询、按设备查询//对话标题
      dialogTitle: '', // 用于控制对话框标题的属性
      isAddMode: true, //是否是新增状态
      //治疗师分页
      resDoctorData: [],
      tableDoctorData: [],
      resDeviceData: [],
      tableDeviceData: [],
      doctorpage: 1,
      doctorsize: 5,
      doctortotal: 0,
      //治疗设备分页
      devicepage: 1,
      devicesize: 5,
      devicetotal: 0,
      //医生管理
      //治疗设备管理
      //治疗室管理
      editRules: {
        detailFormtherapistName: [
        ],
      },
      //下拉框相关内容
      therapistOptions: [], // 存储治疗师信息的下拉框选项
      treatmentRoomOptions: [], // 存储治疗室信息的下拉框选项
      equipmentOptions: [], // 用于存储治疗设备的选项
      //props
      // activeRow: this.$props.activeRow,
      // activeRow2: this.$props.activeRow2
    }
  },
  methods: {
    //获取治疗师排班信息
    async getDoctorList() {
      this.loading = true; // 设置为加载状态
      let tempDate = this.queryData.date;
      if (tempDate) {
        tempDate = moment(tempDate).format('YYYY-MM-DD');
      }
      try {
        let res = await queryAllTherapistScheduleInfo({
          page: this.doctorpage,
          size: this.doctorsize,
          therapistName: this.queryData.doctorname,
          scheduleDate: tempDate,
        });
        // 更新总记录数，用于分页组件计算总页数
        this.doctortotal = res.totalElements;
        this.resDoctorData = res.content.map((i) => ({ ...i }));
        // console.log(this.resDoctorData, "resDoctorData");
        this.tableDoctorData = this.resDoctorData.map(item => {
          const newDoctor = {
            ...item,
            // 将日期数组转换为字符串
            scheduleDate: item.scheduleDate.join('-')
          };
          item.scheduleContent.forEach(slot => {
            let newString = '';
            if (slot.patientName) {
              newString += `病人：${slot.patientName}\n`;
            }
            if (slot.equipmentName) {
              newString += `治疗设备：${slot.equipmentName}\n`;
            }
            if (slot.treatmentRoomName) {
              newString += `治疗室：${slot.treatmentRoomName}\n`;
            }
            // 去除最后一个换行符
            newString = newString.trimEnd();
            newDoctor[slot.scheduleTimeType] = newString;
          });
          return newDoctor;
        });
        // console.log(this.tableDoctorData, "tableDoctorData");
      } finally {
        setTimeout(() => {
          this.loading = false;
        }, 300)
      }
    },
    //点击查询治疗师排班
    queryDoctorSchedule() {
      // 查询排班数据的逻辑
      // console.log("查询治疗师排班", this.queryData);
      this.doctorpage = 1;
      this.getDoctorList();
    },

    //获取治疗设备排班信息
    async getDeviceList() {
      this.loading = true; // 设置为加载状态
      let tempDate = this.queryData.date;
      if (tempDate) {
        tempDate = moment(tempDate).format('YYYY-MM-DD');
      }
      try {
        let res = await queryAllEquipmentScheduleInfo({
          page: this.devicepage,
          size: this.devicesize,
          equipmentName: this.queryData.devicename,
          scheduleDate: tempDate,
        });
        // 更新总记录数，用于分页组件计算总页数
        this.devicetotal = res.totalElements;
        this.resDeviceData = res.content.map((i) => ({ ...i }));
        // console.log(this.resDeviceData, "resDeviceData");
        this.tableDeviceData = this.resDeviceData.map(item => {
          const newDevice = {
            ...item,
            // 将日期数组转换为字符串
            scheduleDate: item.scheduleDate.join('-')
          }
          item.scheduleContent.forEach(slot => {
            let newString = '';
            if (slot.patientName) {
              newString += `病人：${slot.patientName}\n`;
            }
            if (slot.equipmentName) {
              newString += `治疗设备：${slot.equipmentName}\n`;
            }
            if (slot.treatmentRoomName) {
              newString += `治疗室：${slot.treatmentRoomName}\n`;
            }
            // 去除最后一个换行符
            newString = newString.trimEnd();
            newDevice[slot.scheduleTimeType] = newString;
          });
          return newDevice;
        });
        // console.log(this.tableDeviceData, "tableDeviceData");
      } finally {
        setTimeout(() => {
          this.loading = false;
        })
      }
    },
    //点击查询治疗设备排班
    queryDeviceSchedule() {
      // console.log("查询治疗设备排班", this.queryData);
      this.devicepage = 1;
      this.getDeviceList();
    },
    // 确定预约病人
    submitPatient() {
      this.patientSelectionVisible = false;
      let data = this.batchData.find(item => item.batchId === this.selectPatient);
      console.log(data, "data");

      // this.appointmentForm();
    },
    //点击单元格事件
    handleDoctorCellClick(row, column, cell, event) {
      this.editRowColumn = { row, column }
      // console.log(this.batchData, "batchData");
      this.patientSelectionVisible = true;

      // this.isAddMode = false;
      // this.dialogTitle = '编辑排班信息';
      // //点击单元格事件
      // const ignoreLabels = ["医师姓名", "治疗设备/治疗室", "日期"];
      // if (ignoreLabels.includes(column.label)) {
      //     return;
      // }
      // this.dialogVisible = true;
      // // 存储当前点击单元格的行和列的 label
      // this.currentRowLabel = row.therapistName;
      // this.currentColumnLabel = column.label;
      // // 获取当前点击的label所对应的timeSlots里的value
      // const clickedTimeSlot = this.timeSlots.find(slot => slot.display === column.label);
      // const clickedTimeSlotValue = clickedTimeSlot ? clickedTimeSlot.value : null;
      // // console.log(clickedTimeSlotValue, "clickedTimeSlotValue当前点击的scheduleTimeType");
      // console.log('获取到的row:', row);
      // if (clickedTimeSlotValue) {
      //     const matchingSchedule = row.scheduleContent.find(s => s.scheduleTimeType === clickedTimeSlotValue);
      //     console.log("matchingSchedule符合筛选条件的row", matchingSchedule);
      //     if (matchingSchedule) {
      //         this.currentPatient = matchingSchedule.patientName;
      //         this.detailForm = {
      //             ...this.detailForm,
      //             // detailtreatmentName:matchingSchedule.treatmentName,//治疗项目名称
      //             detailFormId: matchingSchedule.id,//排班信息id
      //             detailFormtherapistName: matchingSchedule.therapistName || '',
      //             detailFormtherapistId: matchingSchedule.therapistId || '',
      //             detailFormtreatmentRoomName: matchingSchedule.treatmentRoomName || '',
      //             detailFormequipmentName: matchingSchedule.equipmentName || '',
      //             detailFormscheduleTimeType: clickedTimeSlotValue,
      //             // detailFormpatientName: this.currentPatient,
      //             // detailFormpatientId: matchingSchedule.patientId,
      //             detailFormpatientName: this.activeRow ? this.activeRow.patientName : this.currentPatient,
      //             detailFormpatientId: this.activeRow ? this.activeRow.patientId : matchingSchedule.patientId,
      //             detailFormtreatmentName: this.activeRow2 ? this.activeRow2.treatmentName : matchingSchedule.treatmentName,
      //             detailFormscheduleDate: row.scheduleDate,
      //             equipmentName: row.equipmentName,
      //         }
      //         // console.log(this.detailForm, "this.detailForm");
      //     } else {
      //         this.currentPatient = "";
      //         this.detailForm = {
      //             ...this.detailForm,
      //             detailFormtherapistId: row.therapistId || '',
      //             detailFormscheduleTimeType: clickedTimeSlotValue,
      //             detailFormscheduleDate: row.scheduleDate,
      //             detailFormpatientName: this.activeRow ? this.activeRow.patientName : '',
      //             detailFormpatientId: this.activeRow ? this.activeRow.patientId : '',
      //             detailFormtreatmentName: this.activeRow2 ? this.activeRow2.treatmentName : '',
      //         };
      //         this.isAddMode = true;
      //     }
      // }
      // if (this.detailForm.detailFormtreatmentRoomName) {
      //     this.handleTreatmentRoomChange(this.detailForm.detailFormtreatmentRoomName);
      // }
    },
    // 弹出预约表单
    appointmentForm() {
      let { row, column } = this.editRowColumn;

      this.isAddMode = false;
      this.dialogTitle = '编辑排班信息';
      //点击单元格事件
      const ignoreLabels = ["医师姓名", "治疗设备/治疗室", "日期"];
      if (ignoreLabels.includes(column.label)) {
        return;
      }
      this.dialogVisible = true;
      // 存储当前点击单元格的行和列的 label
      this.currentRowLabel = row.therapistName;
      this.currentColumnLabel = column.label;
      // 获取当前点击的label所对应的timeSlots里的value
      const clickedTimeSlot = this.timeSlots.find(slot => slot.display === column.label);
      const clickedTimeSlotValue = clickedTimeSlot ? clickedTimeSlot.value : null;
      // console.log(clickedTimeSlotValue, "clickedTimeSlotValue当前点击的scheduleTimeType");
      // console.log('获取到的row:', row);
      // console.log(this.currentRowLabel, "currentRowLabel");
      // console.log(this.currentColumnLabel, "currentColumnLabel");
      // console.log(this.clickedTimeSlot, "clickedTimeSlot");
      // console.log(this.clickedTimeSlotValue, "clickedTimeSlotValue");

      if (clickedTimeSlotValue) {
        const matchingSchedule = row.scheduleContent.find(s => s.scheduleTimeType === clickedTimeSlotValue);
        if (matchingSchedule) {
          this.currentPatient = matchingSchedule.patientName;
          this.detailForm = {
            ...this.detailForm,
            // detailtreatmentName:matchingSchedule.treatmentName,//治疗项目名称
            detailFormId: matchingSchedule.id,//排班信息id
            detailFormtherapistName: matchingSchedule.therapistName || '',
            detailFormtherapistId: matchingSchedule.therapistId || '',
            detailFormtreatmentRoomName: matchingSchedule.treatmentRoomName || '',
            detailFormequipmentName: matchingSchedule.equipmentName || '',
            detailFormscheduleTimeType: clickedTimeSlotValue,
            // detailFormpatientName: this.currentPatient,
            // detailFormpatientId: matchingSchedule.patientId,
            detailFormpatientName: this.activeRow ? this.activeRow.patientName : this.currentPatient,
            detailFormpatientId: this.activeRow ? this.activeRow.patientId : matchingSchedule.patientId,
            detailFormtreatmentName: this.activeRow2 ? this.activeRow2.treatmentName : matchingSchedule.treatmentName,
            detailFormscheduleDate: row.scheduleDate,
            equipmentName: row.equipmentName,
          }
          // console.log(this.detailForm, "this.detailForm");
        } else {
          this.currentPatient = "";
          this.detailForm = {
            ...this.detailForm,
            detailFormtherapistId: row.therapistId || '',
            detailFormscheduleTimeType: clickedTimeSlotValue,
            detailFormscheduleDate: row.scheduleDate,
            detailFormpatientName: this.activeRow ? this.activeRow.patientName : '',
            detailFormpatientId: this.activeRow ? this.activeRow.patientId : '',
            detailFormtreatmentName: this.activeRow2 ? this.activeRow2.treatmentName : '',
          };
          this.isAddMode = true;
        }
      }
      if (this.detailForm.detailFormtreatmentRoomName) {
        // this.handleTreatmentRoomChange(this.detailForm.detailFormtreatmentRoomName);
      }
    },
    handleDeviceCellClick(row, column, cell, event) {
      this.isAddMode = false;
      this.dialogTitle = '编辑排班信息';
      //点击单元格事件
      const ignoreLabels = ["医师姓名", "治疗设备/治疗室", "日期"];
      if (ignoreLabels.includes(column.label)) {
        return;
      }
      this.dialogVisible = true;
      // 存储当前点击单元格的行和列的 label
      this.currentRowLabel = row.equipmentName;
      this.currentColumnLabel = column.label;
      // console.log('获取到的equipmentName:和列的 label', this.currentRowLabel, this.currentColumnLabel);
      // 获取当前点击的label所对应的timeSlots里的value
      const clickedTimeSlot = this.timeSlots.find(slot => slot.display === column.label);
      const clickedTimeSlotValue = clickedTimeSlot ? clickedTimeSlot.value : null;
      // console.log(clickedTimeSlotValue, "clickedTimeSlotValue当前点击的scheduleTimeType");
      console.log('获取到的row:', row);
      if (clickedTimeSlotValue) {
        const matchingSchedule = row.scheduleContent.find(s => s.scheduleTimeType === clickedTimeSlotValue);
        console.log("matchingSchedule符合筛选条件的rowDEVICE", matchingSchedule);
        if (matchingSchedule) {
          this.currentPatient = matchingSchedule.patientName;
          this.detailForm = {
            ...this.detailForm,
            detailFormId: matchingSchedule.id,
            detailFormtherapistName: matchingSchedule.therapistName || '',
            detailFormtherapistId: matchingSchedule.therapistId || '',
            detailFormtreatmentRoomName: matchingSchedule.treatmentRoomName || '',
            detailFormequipmentName: matchingSchedule.equipmentName || '',
            detailFormscheduleTimeType: clickedTimeSlotValue,
            // detailFormpatientName: this.currentPatient,
            // detailFormpatientId: matchingSchedule.patientId,
            detailFormpatientName: this.activeRow ? this.activeRow.patientName : this.currentPatient,
            detailFormpatientId: this.activeRow ? this.activeRow.patientId : matchingSchedule.patientId,
            detailFormtreatmentName: this.activeRow2 ? this.activeRow.treatmentName2 : matchingSchedule.treatmentName,
            detailFormscheduleDate: row.scheduleDate,
            equipmentName: row.equipmentName,
          }
          // console.log(this.detailForm, "this.detailForm");
        } else {
          this.currentPatient = "";
          this.detailForm = {
            ...this.detailForm,
            detailFormtherapistName: this.currentRowLabel || '',
            detailFormequipmentName: this.currentRowLabel || '',
            detailFormscheduleTimeType: this.currentColumnLabel,
            detailFormpatientName: this.activeRow ? this.activeRow.patientName : '',
            detailFormpatientId: this.activeRow ? this.activeRow.patientId : '',
            detailFormtreatmentName: this.activeRow2 ? this.activeRow2.treatmentName : '',
          };
          // console.log("没有");
        }
      }
      if (this.detailForm.detailFormtreatmentRoomName) {
        this.handleTreatmentRoomChange(this.detailForm.detailFormtreatmentRoomName);
      }
    },

    //点击新增
    addSchedule() {
      this.dialogTitle = '新增排班信息';
      this.isAddMode = true;
      this.dialogVisible = true;
      this.equipmentOptions = [];
      this.detailForm = {
        detailFormtherapistName: '',
        detailFormtherapistId: null, // 新增初始化治疗师ID字段
        detailFormpatientName: this.activeRow ? this.activeRow.patientName : '',
        detailFormpatientId: this.activeRow ? this.activeRow.patientId : '',
        detailFormtreatmentName: this.activeRow2 ? this.activeRow2.treatmentName : '',
      };
    },

    //dialog点击确认
    async saveSchedule(editFormRef) {
      try {
        const valid = await this.$refs[editFormRef].validate();
        if (valid) {
          // 根据 therapistId 从 therapistOptions 中找到对应的 therapistName
          const therapist = this.therapistOptions.find(t => t.id === this.detailForm.detailFormtherapistId);
          const therapistName = therapist ? therapist.name : '';
          const dataToSend = {
            // detailForm: { ...this.detailForm },
            scheduleTimeType: this.detailForm.detailFormscheduleTimeType,
            patientName: this.detailForm.detailFormpatientName,
            patientId: this.detailForm.detailFormpatientId,
            therapistId: this.detailForm.detailFormtherapistId,
            therapistName: therapistName,
            treatmentRoomName: this.detailForm.detailFormtreatmentRoomName,
            treatmentName: this.detailForm.detailFormtreatmentName,
            treatmentRoomId: this.detailForm.detailFormtreatmentRoomId,
            equipmentName: this.detailForm.detailFormequipmentName,
            scheduleDate: moment(this.detailForm.detailFormscheduleDate).format('YYYY-MM-DD'),
            adviceId: this.activeRow2 ? this.activeRow2.adviceId : '',
          };
          console.log(dataToSend, '点击确认的输出，包含处理后的信息');
          addScheduleInfo(dataToSend)
            .then(response => {
              // 根据接口返回处理成功情况，比如提示用户新增成功等
              console.log("记录新增成功：", response);
              this.$notify({
                title: '提示',
                message: '记录保存成功',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getDoctorList();
              this.getDeviceList();
              this.handleOperationComplete();
            })
        } else {
          // 验证不通过，不调用接口，弹窗不隐藏，这里已经会自动显示红色提示消息（由表单验证规则控制）
          return false;
        }

      } catch (error) {
        console.log(error, "error");
      }
    },

    //点击dialog更新
    async updateSchedule(editFormRef) {
      try {
        const valid = await this.$refs[editFormRef].validate();
        // 根据 therapistId 从 therapistOptions 中找到对应的 therapistName
        const therapist = this.therapistOptions.find(t => t.id === this.detailForm.detailFormtherapistId);
        const therapistName = therapist ? therapist.name : '';
        if (valid) {
          const dataToSend = {
            id: this.detailForm.detailFormId,
            scheduleTimeType: this.detailForm.detailFormscheduleTimeType,
            patientName: this.detailForm.detailFormpatientName,
            patientId: this.detailForm.detailFormpatientId,
            therapistId: this.detailForm.detailFormtherapistId,
            therapistName: therapistName,
            treatmentRoomName: this.detailForm.detailFormtreatmentRoomName,
            treatmentName: this.detailForm.detailFormtreatmentName,
            treatmentRoomId: this.detailForm.detailFormtreatmentRoomId,
            equipmentName: this.detailForm.detailFormequipmentName,
            scheduleDate: moment(this.detailForm.detailFormscheduleDate).format('YYYY-MM-DD'),
            adviceId: this.activeRow2 ? this.activeRow2.adviceId : '',
          };
          console.log(dataToSend, '点击更新的输出，包含处理后的信息');
          // 调用更新接口
          updateScheduleInfo(dataToSend)
            .then(response => {
              console.log("记录更新成功：", response);
              this.$notify({
                title: '提示',
                message: '记录更新成功',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getDoctorList();
              this.getDeviceList();
            });
        } else {
          return false;
        }
      } catch (error) {
        console.log(error, "error");
      }
    },

    //点击删除
    async delSchedule() {
      try {
        await this.$confirm('确定要删除该信息吗？此操作不可恢复。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let id = this.detailForm.detailFormId;
          await deleteScheduleInfo(id);
          this.$message({
            type: 'success',
            message: '信息删除成功'
          });
          this.dialogVisible = false;
          this.doctorpage = 1;
          this.getDoctorList();
          this.devicepage = 1;
          this.getDeviceList();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除操作'
          });
        });
      } catch (error) {
        this.$message({
          type: 'danger',
          message: '删除失败，请稍后再试'
        });
        console.log(error, "error");
      }
    },

    //获取全部治疗师姓名和id 存储成对应新增信息或编辑信息的下拉框 下拉框支持模糊搜索 使用el-select自定义模板下拉框内容左侧显示治疗师姓名右侧显示id
    async queryAllTherapist() {
      try {
        let res = await queryAllTherapistInfo();
        if (res && res.code === 0 && res.content) {
          this.therapistOptions = res.content.map(therapist => ({
            label: therapist.therapistName,
            value: therapist.id,
            id: therapist.id,
            name: therapist.therapistName
          }));
        }
        // console.log("获取全部治疗师姓名和id 存储成对应新增信息或编辑信息的下拉框", this.therapistOptions);
      } catch (error) {
        this.$notify({
          title: '提示',
          message: '网络出错了，请稍后再试',
          type: 'danger'
        });
      }
    },

    //获取治疗室和对应治疗设备的下拉框 当选取治疗室后 里展示对应的治疗设备
    async queryAllTreatmentRoom() {
      try {
        let res = await queryAllTreatmentRoomNameAndId();
        if (res && res.code === 0 && res.content) {
          this.treatmentRoomOptions = res.content.map(room => {
            let equipmentList = [];
            if (room.equipmentName) {
              equipmentList = room.equipmentName.split(',');
            }
            return {
              ...room,
              equipmentList: equipmentList
            };
          });
        }
        // console.log("获取治疗室和对应治疗设备的下拉框", this.treatmentRoomOptions);
      } catch (error) {
        this.$notify({
          title: '提示',
          message: '网络出错了，请稍后再试',
          type: 'danger'
        });
      }
    },
    //切换治疗室和对应治疗设备
    handleTreatmentRoomChange(room) {
      const selectedRoom = this.treatmentRoomOptions.find(
        r => r.treatmentRoomName === room
      );
      // console.log(selectedRoom, "selectedRoom");
      this.equipmentOptions = selectedRoom.equipmentList || [];
      // if (this.equipmentOptions.length > 0) {
      //     if(this.detailForm.detailFormequipmentName){
      //         this.detailForm.detailFormequipmentName = this.detailForm.detailFormequipmentName;
      //     }else{
      //         this.detailForm.detailFormequipmentName = this.equipmentOptions[0];
      //     }
      // } else {
      //     this.detailForm.detailFormequipmentName = '';
      // }
      if (this.equipmentOptions.length > 0) {
        if (this.detailForm.detailFormequipmentName) {
          this.detailForm.detailFormequipmentName = this.detailForm.detailFormequipmentName;
        } else {
          this.detailForm.detailFormequipmentName = this.equipmentOptions[0];
        }
      }
      this.detailForm.detailFormtreatmentRoomId = selectedRoom.id;
      // console.log(this.detailForm.detailFormequipmentName, "detailFormequipmentName");

    },
    //点击排班查询，按医师/设备查询
    handlequeryTabClick(tab) {
      this.queryTab = tab.label;
      // console.log(this.queryTab, "this.queryTab");
    },

    //关闭dialog时调用的方法
    clearFormValidate() {
      // this.$refs.editFormRef.clearValidate();
      this.detailForm = {};
    },

    // 处理每页显示条数变化的逻辑
    handleDoctorSizeChange(val) {
      this.doctorsize = val;
      this.getDoctorList();
    },
    // 处理当前页码变化的逻辑
    handleDoctorCurrentChange(val) {
      this.doctorpage = val;
      this.getDoctorList();
    },
    // 处理每页显示条数变化的逻辑
    handleDeviceSizeChange(val) {
      this.devicesize = val;
      this.getDeviceList();
    },
    // 处理当前页码变化的逻辑
    handleDeviceCurrentChange(val) {
      this.devicepage = val;
      this.getDeviceList();
    },

    // 修改table cell样式的方法，使单元格内容居中显示
    cellStyle({ row, column, rowIndex, columnIndex }) {
      return "text-align:center;";
    },

    //传给治疗预约页面的值
    handleOperationComplete() {
      this.$emit('operationComplete');
    }
  },
  props: {
    activeRow: {
      type: Object,
      default: null,
    },
    activeRow2: {
      type: Object,
      default: null,
    },
    timestamp: {
      type: Number,
      default: null,
    },
    batchData: {
      type: Array,
      default: () => ([])
    }
  },
  watch: {
    activeRow2: function (val) {
      if (val) {
        console.log("排班组件中的activeRow2", val);
      }
    },
    activeRow: function (val) {
      if (val) {
        console.log("排班组件中的activeRow", val);
      }
    },
    timestamp: function (val) {
      console.log("排班组件中的timestamp", val);
      this.queryAllTherapist();
      this.queryAllTreatmentRoom();
      this.getDoctorList();
      this.getDeviceList();
    }
  },
  mounted() {
    this.queryAllTherapist();
    this.queryAllTreatmentRoom();
    this.getDoctorList();
    this.getDeviceList();
    console.log("scheduling-this.$props.activeRow", this.$props.activeRow);
    console.log("scheduling-this.$props.activeRow2", this.$props.activeRow2);
    console.log("timestamp", this.timestamp);
  }
};

</script>
<style lang="scss" scoped>
.demo-form-inline {
  text-align: center;
  flex-wrap: nowrap;

  .el-form-item {
    margin: 5px 10px;
  }
}

.head-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  column-gap: 25px;
}

.head-container>div,
.head-container el-radio-group,
.head-container el-button {
  display: flex;
  align-items: center;
}

.chaxun {
  margin-left: 15px;
}

.card-style {
  background-color: #f0f0f5;
  border: 1px solid #e0e0e5;
  border-radius: 5px;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: inline-block;
  white-space: pre-wrap;
  font-size: 14px;
  width: auto;
  min-width: 100px;
  max-width: 300px;
}

.loading {
  opacity: 0.5;
  cursor: wait;
}

/deep/.el-select {
  width: 100%;
}

/deep/.el-dialog__body {
  padding: 20px 50px 0px 10px;
}

/deep/.el-table__body-tr:hover {
  background-color: inherit;
  color: inherit;
}

/deep/.el-table__cell:hover {
  background-color: rgb(238, 241, 246) !important;
}

.head-container .el-button+.el-button {
  margin-left: 30px !important;
}

.el-pagination {
  padding-top: 15px;
  text-align: center;
}

.el-dialog p {
  font-size: 16px;
  color: #333;
  margin-left: 20px;
}

.detialdate {
  width: 100%;
}

/deep/.el-table {
  table-layout: auto;
  width: 100%;
  /* 确保表格宽度占满父元素 */
}

.patient-info-container {
  margin-top: 15px;
  padding: 10px;
  border: 1px solid #e0e0e5;
  border-radius: 5px;
  background-color: #f0f0f5;
  display: flex; // 使用 flex 布局
  align-items: center;
}

.patient-info-item {
  margin: 0 10px;
  margin: 5px 0;
  font-size: 14px;
  color: #333;
}

.info-label {
  font-weight: bold;
  margin-right: 5px;
}

.info-value {
  display: inline-block;
  background-color: #fff;
  /* 增加白色背景 */
  border: 1px solid #ddd;
  /* 添加淡灰色边框 */
  border-radius: 3px;
  /* 圆角 */
  padding: 3px 6px;
  /* 增加内边距 */
  color: #333;
  /* 文字颜色 */
  min-width: 80px;
  /* 设置最小宽度 */
  text-align: center;
  /* 文字居中 */
}
</style>
